package cn.ffcs.product.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.List;

import org.apache.commons.io.FileUtils;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;

import cn.ffcs.base.service.BaseService;
import cn.ffcs.common.dao.IAttachDAO;
import cn.ffcs.common.model.Attach;
import cn.ffcs.product.dao.ProductReferenceDAO;
import cn.ffcs.product.model.ProductReference;
import cn.ffcs.security.model.User;
import cn.ffcs.util.context.ApplicationContextUtil;
import cn.ffcs.util.properties.PropertiesUtil;

/**
 * 产品资料服务层实现<br/>
 * <table>
 * <tr>
 * <td>负责人/principal:</td>
 * <td colspan="2">liuzhh</td>
 * <tr>
 * <td>修改记录/revision:</td>
 * <td colspan="2"></td>
 * </tr>
 * <tr>
 * <td>日期:</td>
 * <td>修改人:</td>
 * <td>修改说明:</td>
 * </tr>
 * <tr>
 * <td></td>
 * <td></td>
 * <td></td>
 * </tr>
 * </table>
 * @author liuzhh
 * @version $Id$
 */
public class ProductReferenceService<P extends ProductReference> extends
        BaseService<P> implements IProductReferenceService<P>
{
    private static final int BUFFER_SIZE = 512 * 1024;

    /** 附件DAO **/
    private IAttachDAO attachDAO;

    private ProductReferenceDAO productReferenceDAO;
    
    /**
     * 新增或修改操作
     * @param baseEntity
     */
    public void saveOrUpdate(P productReference)
    {
        if (productReference != null)
        {
            if (productReference.getId() == null || productReference.getId() == 0)
            {   
                if("".equals(productReference.getCreator().trim())){
                    //设置操作人
                    User currUser=ApplicationContextUtil.getUserContextObject().getCurrUser();
                    if (currUser!=null)
                        productReference.setCreator(currUser.getUserID());
                }
                //设置有效时间
                productReference.setBegin(productReferenceDAO.getCurrSysdate());
                Long l=Long.valueOf("9783941568000");
                Date end=new Date(l);
                productReference.setEnd(end);
                //保存数据
                productReferenceDAO.save(productReference);
            }
            else
            {
                productReferenceDAO.update(productReference);
            }
        }
    }
    
    /**
     * 
     * TODO 保存附件
     * @param attach
     */
    public void saveAttach(Attach attach){
        attachDAO.save(attach);
    }
    
    private static void copy(File src, File dst) {
        try  {
                  InputStream in = null ;
                  OutputStream out = null ;
                   try  {                
                      in = new BufferedInputStream( new FileInputStream(src), BUFFER_SIZE);
                      out = new BufferedOutputStream( new FileOutputStream(dst), BUFFER_SIZE);
                       byte [] buffer = new byte [BUFFER_SIZE];
                       while (in.read(buffer) > 0 )  {
                          out.write(buffer);
                      } 
                   } finally  {
                       if ( null != in)  {
                          in.close();
                      } 
                        if ( null != out)  {
                          out.close();
                      } 
                  } 
               } catch (Exception e)  {
                  e.printStackTrace();
              } 

       }

    private static String getExtention(String fileName) {
        int pos = fileName.lastIndexOf(".");
        return fileName.substring(pos);
       }
    
    /**
     * 保存产品资料操作
     * @param contextPath 
     */
    @SuppressWarnings("unchecked")
    public boolean saveProductReferenceInfo(String contextPath, P productReference,
            List<File> uploads, List<String> fileNames, String[] publishIDs,
            String[] attachIDs, String[] delIDs, List<String> isPublishs,
            List<String> isFtp)
    {

        // 保存产品资料数据
        saveOrUpdate(productReference);

        // 保存附件
        if (uploads != null && isPublishs != null && uploads.size() == isPublishs.size())
        {
            int i = 0;
            for (i = 0; i < uploads.size(); i++)
            {
                try
                {
                    if(isFtp.get(i).equals("0")){
                        File file = uploads.get(i);
                        byte[] result = new byte[BUFFER_SIZE];
                        result = FileUtils.readFileToByteArray(file);
                        FileUtils.forceDelete(file);
                        String fileName = fileNames.get(i);
                        String fullName = fileName;
                        String name = fullName.substring(0, fullName.lastIndexOf("."));
                        String prefix = fullName.substring(
                                fullName.lastIndexOf(".") + 1, fullName.length());
    
                        Attach attach = new Attach();
                        attach.setContent(result);
                        attach.setFileType("FILE");
                        attach.setFullName(fullName);
                        attach.setName(name);
                        attach.setPrefix(prefix);
                        attach.setRefEntity(productReference.getClass().getName());
                        attach.setRefEntityID(productReference.getId().toString());
                        attach.setIsPublish(Integer.parseInt(isPublishs.get(i).toString()));
                        //设置基本信息
                        setBaseInfo(attach);
    
                        attachDAO.save(attach);
                    }
                    if(isFtp.get(i).equals("1")){
                        File file = uploads.get(i);
                        String productReferenceId = productReference.getId().toString();
                        String fileName = fileNames.get(i);
                        String fullName = fileName;
                        String name = fullName.substring(0, fullName.lastIndexOf("."));
                        String prefix = fullName.substring(
                                fullName.lastIndexOf(".") + 1, fullName.length());
                        
                        Long dateFile= new Date().getTime();
                        String urlFileName = productReferenceId + "_" + dateFile + "." + prefix;
                        String saveDirectory = contextPath + PropertiesUtil.readValue(
                                "/poc-ftp.properties", "ftp.path");
                        //保存绝对路径
                        String saveFilePath = saveDirectory + urlFileName;
                        FileUtils.copyFile(file, new File(saveFilePath));
                        
                        //byte[] result = new byte[BUFFER_SIZE];
                        //result = FileUtils.readFileToByteArray(file);
                        
                        FileUtils.forceDelete(file);
    
                        Attach attach = new Attach();
                        //attach.setContent(result);
                        attach.setFileType("FILE");
                        attach.setFullName(fullName);
                        attach.setName(name);
                        attach.setPrefix(prefix);
                        attach.setRefEntity(productReference.getClass().getName());
                        attach.setRefEntityID(productReference.getId().toString());
                        attach.setIsPublish(Integer.parseInt(isPublishs.get(i).toString()));
                        attach.setUrlFileName(urlFileName);
                        attach.setIsFtp(1);
                        //设置基本信息
                        setBaseInfo(attach);
    
                        attachDAO.save(attach);
                        
                    }
                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }

        // 修改附件是否为发布
        int iPub = 0;
        int iAttach = 0;
        if (publishIDs != null)
        {
            iPub = publishIDs.length;
        }
        if (attachIDs != null)
        {
            iAttach = attachIDs.length;
        }
        String[] unpubIDs = new String[iAttach - iPub];
        for (String pID : publishIDs)
        {
            Attach attach = (Attach) attachDAO.findById(Integer.parseInt(pID));
            attach.setIsPublish(1);
            attachDAO.update(attach);
        }
        int i = 0;
        for (String attachID : attachIDs)
        {
            boolean isExist = false;
            for (String pID : publishIDs)
            {
                if (attachID.equalsIgnoreCase(pID))
                {
                    isExist = true;
                }
            }
            if (!isExist) {
                unpubIDs[i] = attachID;
                i++;
            }
        }
        for (String unpubID : unpubIDs)
        {
            Attach attach = (Attach) attachDAO.findById(Integer
                    .parseInt(unpubID));
            attach.setIsPublish(0);
            attachDAO.update(attach);
        }

        // 删除附件
        if (delIDs != null && delIDs.length > 0)
        {
            for (String id : delIDs)
            {
                attachDAO.deleteById(id);
            }
        }

        return true;
    }

    /**
     * 删除操作
     * @param baseEntity
     */
    @SuppressWarnings("unchecked")
    public void remove(P productReference)
    {
        //删除附件
        Criterion cond1 = Restrictions.eq("refEntity", productReference.getClass().getName());
        Criterion cond2 = Restrictions.eq("refEntityID", productReference.getId().toString());
        Criterion condAttach = Restrictions.and(cond1, cond2);
        List<Attach> lAttach=attachDAO.findBy(condAttach);
        if (lAttach!=null && lAttach.size()>0){
            for (Attach a:lAttach){
                attachDAO.delete(a);
            }
        }
        
        //删除资料
        super.remove(productReference);
//        if (productReference != null && productReference.getId() != 0)
//        {
//            productReference = findById(productReference.getId());
//            if (productReference != null)
//            {
//                //获取当前时间
//                Date curr=getCurrSysdate();
//                productReference.setEnd(curr);
//                update(productReference);
//                //baseDAO.delete(baseEntity);
//            }
//        }
    }
    
    /**
     * @return the attachDAO
     */
    public IAttachDAO getAttachDAO()
    {
        return attachDAO;
    }

    /**
     * @param attachDAO the attachDAO to set
     */
    public void setAttachDAO(IAttachDAO attachDAO)
    {
        this.attachDAO = attachDAO;
    }
    public ProductReferenceDAO getProductReferenceDAO()
    {
        return productReferenceDAO;
    }
    public void setProductReferenceDAO(ProductReferenceDAO productReferenceDAO)
    {
        this.productReferenceDAO = productReferenceDAO;
    }

}
